import {
  checkPermission
} from '../../utils/permission';
import util from '@/utils/fromat_clock.js'
export default {
  namespaced: true,
  state: () => ({
    clockRecords: [], // 打卡记录 [上班记录，下班记录]
    status: 0, // 打卡状态 0 未打卡 1已打卡
    signType: 0, // 打卡类型 0上班打卡 1下班打卡
    is_out: 1, // 打卡样式 1上班 2下班
    now_time_stop: '', // 已打卡时间,
    status_clock: 1, // 0上班打卡时,已打卡的样式 1下班时，打卡的样式
    checkInDate: '', // 当天的打卡日期
    isCheckIn: 0, // 是否签到 1打卡，0未打卡
    onWorkTime: '', // 上班打卡时间
    offDutyTime: '', // 下班打卡时间
    connectionTimes: 0, // 将重试次数存入 state
  }),
  mutations: {
    // 新增 mutation 更新重试次数
    UPDATE_CONNECTION_TIMES(state, times) {
      state.connectionTimes = times;
    },
    // 更新打卡记录和状态
    UPDATE_CLOCK_STATE(state, payload = {}) {
      state.status_clock = payload.status_clock ?? state.status_clock;
      state.clockRecords = payload.clockRecords || state.clockRecords;
      state.status = payload.status ?? state.status; // 使用 ?? 避免 0覆盖
      state.signType = payload.signType ?? state.signType;
      state.is_out = payload.is_out ?? state.is_out;
      state.now_time_stop = payload.now_time_stop || state.now_time_stop;
    },
    // 更新当天的考勤信息
    UPDATE_RECORDS_STATE(state, payload = {}) {
      state.checkInDate = payload.checkInDate || state.checkInDate
      state.isCheckIn = payload.isCheckIn ?? state.isCheckIn
      state.onWorkTime = payload.onWorkTime || state.onWorkTime
      state.offDutyTime = payload.offDutyTime || state.offDutyTime
    },
    // 重置所有状态
    RESET_STATE(state) {
      console.log('进行本地的重置')
      state.clockRecords = [];
      state.status = 0;
      state.signType = 0;
      state.is_out = 1;
      state.now_time_stop = '';
      state.status_clock = 1;
      state.isCheckIn = 0;
      state.onWorkTime = ''
      state.offDutyTime = ''
    },


    // 更新所有设备的数据
    UPDATE_RECORDS_STATE_PERSONAL(state, Data) {
      const today = util.getTime(new Date());
      state.isCheckIn = Data.isCheckIn ?? 0;
      state.checkInDate = Data.checkInDate || today;
      state.onWorkTime = Data.onWorkTime;
      state.offDutyTime = Data.offDutyTime;

      // 如果当天已打卡
      if (state.isCheckIn === 1) {
        // 更新为“已上班打卡”状态
        state.status = 1;
        state.signType = 0;
        state.is_out = 1;
        state.status_clock = 0;

        // 如果下班时间存在，更新为“已下班打卡”状态
        if (state.offDutyTime && state.offDutyTime !== '' && state.offDutyTime !== '00:00:00') {
          state.status = 1;
          state.status_clock = 1;
          state.signType = 1;
        }
      }
      
    }
  },
  actions: {
    // 保存打卡状态到本地存储
    saveClockState({
      state
    }) {
      const clockState = {
        clockRecords: [...state.clockRecords], // 深拷贝数组
        status: state.status,
        status_clock: state.status_clock,
        signType: state.signType,
        is_out: state.is_out,
        now_time_stop: state.now_time_stop,
        saveDate: util.getTime(new Date()), // 保存当前日期
        checkInDate: state.checkInDate,
        isCheckIn: state.isCheckIn,
        onWorkTime: state.onWorkTime,
        offDutyTime:state.offDutyTime
      }
      uni.setStorageSync('clockState', clockState);
    },
    // 本地存储加载打卡状态
    loadClockState({
      commit
    }) {
      console.log('加载了本地的打卡状态')
      const clockState = uni.getStorageSync('clockState')
      console.log(clockState)
      if (clockState && clockState.saveDate) {
        console.log('加载成功')
        commit('UPDATE_CLOCK_STATE', clockState)
      }
    },
    // 检查是否需要重置状态（新的一天）
     async checkNewDay({
      commit,
      dispatch
    }) {
      console.log('检查新的一天')
      const today = util.getTime(new Date());
      const clockState = uni.getStorageSync('clockState')
      // 如果没有存储状态（首次加载）或者是新的一天，重置状态
      if (!clockState || clockState.saveDate !== today) {
        commit('RESET_STATE')
         try {
            await dispatch('getRecordsData')
          } finally {
            dispatch('saveClockState') // 无论成功失败都保存
          }
        return true
      }
      return false
    },
    /**
     * @description 获取员工个人当天的考勤信息,这里的逻辑问题已修改
     * @return {object}
     */
    async getRecordsData({
      commit,
      dispatch,
      state // 解构出state
    }) {
      try {
        console.log('获取员工共当天的考勤信息')
        const {
          data: res
        } = await uni.$http.get('/attendance/getRecords/personal')
        if (!res.data) {
          console.warn('获取个人考勤记录接口未返回有效data')
          commit('RESET_STATE')
          return;
        }
        const RecordState = {
          checkInDate: res.data.checkInDate,
          isCheckIn: res.data.isCheckIn,
          onWorkTime: res.data.onWorkTime,
          offDutyTime: res.data.offDutyTime,
        }
        // 这里通过上面的数据，对打卡状态进行更新
        commit('UPDATE_RECORDS_STATE_PERSONAL', RecordState)
        await dispatch('saveClockState')
        commit('UPDATE_CONNECTION_TIMES', 0); // 成功后重置重试次数
      } catch (error) {
        setTimeout(async () => {
          uni.hideToast(); // 清除之前的提示
          if (state.connectionTimes >= 2) {
            uni.$showMsg('请求多次失败，请重启小程序');
            commit('UPDATE_CONNECTION_TIMES', 0); // 重置次数
            return;
          }
          commit('UPDATE_CONNECTION_TIMES', state.connectionTimes + 1);
          uni.$showMsg(`网络不佳，正在尝试重新连接(${state.connectionTimes}/2)`,1500)
          await dispatch('getRecordsData');
        }, 5000);
      }
    },
  },
  getters: {}
}